package com.edu.servlet;

import com.edu.bean.SubjectInfo;
import com.edu.bean.StudentScore;
import com.edu.service.AdminSubjectService;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/admin/subject/*")
public class AdminSubjectServlet extends HttpServlet {
    private AdminSubjectService adminSubjectService = new AdminSubjectService();
    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String pathInfo = request.getPathInfo();
        if (pathInfo == null) {
            pathInfo = "/";
        }

        switch (pathInfo) {
            case "/list":
                listSubjects(request, response);
                break;
            case "/get":
                getSubject(request, response);
                break;
            case "/scores":
                listScores(request, response);
                break;
            case "/add-score":
                showAddScore(request, response);
                break;
            default:
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String pathInfo = request.getPathInfo();
        if (pathInfo == null) {
            pathInfo = "/";
        }

        switch (pathInfo) {
            case "/add":
                addSubject(request, response);
                break;
            case "/update":
                updateSubject(request, response);
                break;
            case "/delete":
                deleteSubject(request, response);
                break;
            case "/add-score":
                addScore(request, response);
                break;
            case "/update-score":
                updateScore(request, response);
                break;
            case "/delete-score":
                deleteScore(request, response);
                break;
            default:
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }

    private void listSubjects(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int page = 1;
        int limit = 10;
        String pageStr = request.getParameter("page");
        String search = request.getParameter("search");

        if (pageStr != null && !pageStr.isEmpty()) {
            page = Integer.parseInt(pageStr);
        }

        Map<String, Object> result = adminSubjectService.adminListSubjects(page, limit, search);
        List<SubjectInfo> subjectList = (List<SubjectInfo>) result.get("list");
        int total = (Integer) result.get("total");

        request.setAttribute("subjectList", subjectList);
        request.setAttribute("currentPage", page);
        request.setAttribute("totalPages", (int) Math.ceil((double) total / limit));
        request.setAttribute("totalCount", total);
        request.setAttribute("search", search);

        request.getRequestDispatcher("/admin/subject-list.jsp").forward(request, response);
    }

    private void getSubject(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String idStr = request.getParameter("id");
        if (idStr != null && !idStr.trim().isEmpty()) {
            SubjectInfo subject = adminSubjectService.adminGetSubject(Integer.parseInt(idStr));
            if (subject != null) {
                request.setAttribute("subject", subject);
                request.getRequestDispatcher("/admin/subject-edit.jsp").forward(request, response);
                return;
            }
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        } else {
            request.getRequestDispatcher("/admin/subject-add.jsp").forward(request, response);
        }
    }

    private void addSubject(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/json;charset=utf-8");
        Map<String, Object> result = new HashMap<>();

        try {
            SubjectInfo subject = new SubjectInfo();
            subject.setSubjectName(request.getParameter("subjectName"));
            subject.setTeacherId(Integer.parseInt(request.getParameter("teacherId")));
            subject.setClassroom(request.getParameter("classroom"));
            subject.setWeekDay(Integer.parseInt(request.getParameter("weekDay")));
            subject.setClassTime(request.getParameter("classTime"));

            boolean success = adminSubjectService.adminAddSubject(subject);
            result.put("success", success);
            if (!success) {
                result.put("message", "该时间段已被占用");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "系统错误");
        }

        objectMapper.writeValue(response.getWriter(), result);
    }

    private void updateSubject(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/json;charset=utf-8");
        Map<String, Object> result = new HashMap<>();

        try {
            SubjectInfo subject = new SubjectInfo();
            subject.setSubjectId(Integer.parseInt(request.getParameter("subjectId")));
            subject.setSubjectName(request.getParameter("subjectName"));
            subject.setTeacherId(Integer.parseInt(request.getParameter("teacherId")));
            subject.setClassroom(request.getParameter("classroom"));
            subject.setWeekDay(Integer.parseInt(request.getParameter("weekDay")));
            subject.setClassTime(request.getParameter("classTime"));

            boolean success = adminSubjectService.adminUpdateSubject(subject);
            result.put("success", success);
            if (!success) {
                result.put("message", "该时间段已被占用");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "系统错误");
        }

        objectMapper.writeValue(response.getWriter(), result);
    }

    private void deleteSubject(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/json;charset=utf-8");
        Map<String, Object> result = new HashMap<>();

        String idStr = request.getParameter("id");
        if (idStr != null && !idStr.trim().isEmpty()) {
            boolean success = adminSubjectService.adminDeleteSubject(Integer.parseInt(idStr));
            result.put("success", success);
            if (!success) {
                result.put("message", "删除失败");
            }
        } else {
            result.put("success", false);
            result.put("message", "参数错误");
        }

        objectMapper.writeValue(response.getWriter(), result);
    }

    private void listScores(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 获取分页参数
        int pageSize = 10; // 每页显示10条
        int currentPage = 1; // 默认第一页
        String pageStr = request.getParameter("page");
        if (pageStr != null && !pageStr.trim().isEmpty()) {
            try {
                currentPage = Integer.parseInt(pageStr);
                if (currentPage < 1) {
                    currentPage = 1;
                }
            } catch (NumberFormatException e) {
                // 解析失败，使用默认值
            }
        }

        // 获取学科ID
        Integer subjectId = null;
        String subjectIdStr = request.getParameter("subjectId");
        if (subjectIdStr != null && !subjectIdStr.trim().isEmpty()) {
            try {
                subjectId = Integer.parseInt(subjectIdStr);
            } catch (NumberFormatException e) {
                // 解析失败，使用默认值
            }
        }

        // 获取总记录数和总页数
        int totalCount = adminSubjectService.adminGetScoreTotalCount(subjectId);
        int totalPages = (totalCount + pageSize - 1) / pageSize;

        // 校正当前页码
        if (currentPage > totalPages) {
            currentPage = totalPages;
        }
        if (currentPage < 1) {
            currentPage = 1;
        }

        // 获取当前页的数据
        List<StudentScore> scoreList = adminSubjectService.adminListScoresByPage(subjectId, currentPage, pageSize);

        // 设置分页相关的属性
        request.setAttribute("scoreList", scoreList);
        request.setAttribute("currentPage", currentPage);
        request.setAttribute("totalPages", totalPages);
        request.setAttribute("totalCount", totalCount);
        request.setAttribute("subjectId", subjectId);
        request.setAttribute("subjectList", adminSubjectService.adminListSubjects());

        request.getRequestDispatcher("/admin/score-list.jsp").forward(request, response);
    }

    private void showAddScore(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setAttribute("studentList", adminSubjectService.adminListStudents());
        request.setAttribute("subjectList", adminSubjectService.adminListSubjects());
        request.getRequestDispatcher("/admin/score-add.jsp").forward(request, response);
    }

    private void addScore(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/json;charset=utf-8");
        Map<String, Object> result = new HashMap<>();

        try {
            StudentScore score = new StudentScore();
            score.setStudentId(Integer.parseInt(request.getParameter("studentId")));
            score.setSubjectId(Integer.parseInt(request.getParameter("subjectId")));
            score.setScore(Double.parseDouble(request.getParameter("score")));

            boolean success = adminSubjectService.adminAddScore(score);
            result.put("success", success);
            if (!success) {
                result.put("message", "该学生已有此学科成绩");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "系统错误");
        }

        objectMapper.writeValue(response.getWriter(), result);
    }

    private void updateScore(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/json;charset=utf-8");
        Map<String, Object> result = new HashMap<>();

        try {
            StudentScore score = new StudentScore();
            score.setScoreId(Integer.parseInt(request.getParameter("scoreId")));
            score.setScore(Double.parseDouble(request.getParameter("score")));

            boolean success = adminSubjectService.adminUpdateScore(score);
            result.put("success", success);
            if (!success) {
                result.put("message", "更新失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "系统错误");
        }

        objectMapper.writeValue(response.getWriter(), result);
    }

    private void deleteScore(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/json;charset=utf-8");
        Map<String, Object> result = new HashMap<>();

        String idStr = request.getParameter("id");
        if (idStr != null && !idStr.trim().isEmpty()) {
            boolean success = adminSubjectService.adminDeleteScore(Integer.parseInt(idStr));
            result.put("success", success);
            if (!success) {
                result.put("message", "删除失败");
            }
        } else {
            result.put("success", false);
            result.put("message", "参数错误");
        }

        objectMapper.writeValue(response.getWriter(), result);
    }
}